<template>
  <a-card :bordered="false">
      <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" :hidden="disabled" :disabled="isDisabledAuth('erpAchievementsExtractionDt:add')">新增</a-button>
      <!--<a-button type="primary" icon="download" @click="handleExportXls('绩效提取单明细')" :disabled="isDisabledAuth('erpAchievementsExtractionDt:export')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import" :disabled="isDisabledAuth('erpAchievementsExtractionDt:import')">导入</a-button>
      </a-upload>
      -->
      <!-- 高级查询区域 -->
      <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->




<!--      <a-dropdown v-if="selectedRowKeys.length > 0">-->
<!--        <a-menu slot="overlay">-->
<!--          <a-menu-item key="1" @click="batchDel" :disabled="isDisabledAuth('erpAchievementsExtractionDt:delete')"><a-icon type="delete"/>删除</a-menu-item>-->
<!--        </a-menu>-->
<!--        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>-->
<!--      </a-dropdown>-->
<!--      <a-popover title="自定义列" trigger="click" placement="leftBottom">-->
<!--        <template slot="content">-->
<!--          <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">-->
<!--            <a-row>-->
<!--              <template v-for="(item,index) in defColumns">-->
<!--                <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">-->
<!--                  <a-col :span="12"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>-->
<!--                </template>-->
<!--              </template>-->
<!--            </a-row>-->
<!--          </a-checkbox-group>-->
<!--        </template>-->
<!--        <a style="float: right;"><a-icon type="setting" :style='iconStyle'/></a>-->
<!--      </a-popover>-->
    </div>

    <!-- table区域-begin -->
    <div>
<!--      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">-->
<!--        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项-->
<!--        <a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
<!--      </div>-->
<!--      :rowSelection="{onChange: onSelectChange}"-->
<!--      :customRow="customRow"-->
<!--      :scroll="{x:true}"-->
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:scrollX}"
        :components="draggableComponent"
        bordered
        rowKey="key"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="disabled?null:{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
            <a-button
                class="ruleButton"
                :ghost="true"
                type="primary"
                icon="edit"
                @click="handleEdit(record)"
                :hidden="disabled"
                :disabled="isDisabledAuth('erpAchievementsExtractionDt:edit')"
        />
        <a-divider type="vertical"/>
        <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.key)">
            <a-button
                    class="ruleButton"
                    :ghost="true"
                    type="primary"
                    icon="delete"
                    :hidden="disabled"
                    :disabled="isDisabledAuth('erpAchievementsExtractionDt:delete')"/>
        </a-popconfirm>
        </span>
<!--        <a slot="xmmc" slot-scope="text, record" @click="onDetail(record.projectId)">{{ !text ? '' : filterMultiDictText(this.dictOptions['projectId'], text + '') }}</a>-->

      </a-table>
    </div>
    <!-- 项目详情开始 -->
    <erp-project-report-modal  ref="projectModalForm"></erp-project-report-modal>
    <!-- 项目详情结束 -->

    <erp-achievements-extraction-dt-modal ref="modalForm" @dataOne="dataOne" :dataSource="dataSource" @submitForm="submitForm" @ok="modalFormOk"></erp-achievements-extraction-dt-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ErpAchievementsExtractionDtModal from './modules/ErpAchievementsExtractionDtModal'
  import { getAction,postAction } from '@/api/manage'
  import {DisabledAuthFilterMixin} from '@/mixins/DisabledAuthFilterMixin'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import Vue from 'vue';
  import { filterObj } from '@/utils/util'


  export default {
    name: 'ErpAchievementsExtractionDtList',
    mixins:[JeecgListMixin, mixinDevice, DisabledAuthFilterMixin],
    components: {
      ErpAchievementsExtractionDtModal,
      ErpProjectReportModal: () => import('@/views/erp/report/project/modules/ErpProjectReportModal')
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
    },
    data () {
      return {
        params: {
          mainId: null
        },
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        /* 数据源 */
        dataSource: [],
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading: false,
        /* table选中keys */
        selectedRowKeys: [],
        /* table选中records */
        selectionRows: [],
        /* 查询折叠 */
        toggleSearchStatus: false,
        /* 高级查询条件生效状态 */
        superQueryFlag: false,
        /* 高级查询条件 */
        superQueryParams: '',
        /** 高级查询拼接方式 */
        superQueryMatchType: 'and',
        iconStyle: { 'font-size': '18px', 'cursor': 'pointer' },
        colsettings: ':colsettings',

        description: '绩效提取单明细管理页面',
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'项目名称',
            align:"center",
            dataIndex: 'projectId',
            scopedSlots: { customRender: 'xmmc' },
            customRender: (text,r) => {
              if (!text) {
                return ''
              } else {
                return <a v-on:click={(e) => this.onDetail(text)}>{ filterMultiDictText(this.dictOptions['projectId'], text + '') }</a>;
              }
            },
            // customRender: (text, r) => {
            //   if (!text) {
            //     return ''
            //   } else {
            //     return filterMultiDictText(this.dictOptions['projectId'], text + '')
            //   }
            // },
            width:96,
            ellipsis: true,
          },
          // {
          //   title:'项目名称',
          //   align:"center",
          //   dataIndex: 'projectName',
          // },
          {
            title:'业绩归属年度',
            align:"center",
            dataIndex: 'year',
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['yjgsYear'], text + '')
              }
            },
            width:110,
            ellipsis: true,
          },
          {
            title:'签订单位',
            align:"center",
            dataIndex: 'signUnit',
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['signUnit'], text + '')
              }
            },
            width:200,
            ellipsis: true,
          },
          {
            title:'业务名称',
            align:"center",
            dataIndex: 'taskId',
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['taskId'], text + '')
              }
            },
            width:422,
            ellipsis: true,
          },
          // {
          //   title:'任务id',
          //   align:"center",
          //   dataIndex: 'taskId',
          // },
          {
            title:'费用所属团队',
            align:"center",
            dataIndex: 'feeTeamId',
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['teamId'], text + '')
              }
            },
            width:262,
            ellipsis: true,
          },
          // {
          //   title:'费用所属团队名称',
          //   align:"center",
          //   dataIndex: 'feeTeamName',
          // },

          {
            title:'费用所属年度',
            align:"center",
            dataIndex: 'feeYear',
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['feeYear'], text + '')
              }
            },
            width:110,
            ellipsis: true,
          },
          {
            title:'合同额（元）',
            align:"center",
            dataIndex: 'contractAmount',
            width:110,
            ellipsis: true,
          },
          {
            title:'分配合同额（元）',
            align:"center",
            dataIndex: 'taskContractAmount',
            width:110,
            ellipsis: true,
          },
          {
            title:'回款额（元）',
            align:"center",
            dataIndex: 'realCollectionPaymentMoney',
            width:110,
            ellipsis: true,
          },
          {
            title:'审批级别',
            align:"center",
            dataIndex: 'approvalLevel',
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['approvalLevel'], text + '')
              }
            },
            width:110,
            ellipsis: true,
          },
          {
            title:'难易程度',
            align:"center",
            dataIndex: 'difficultyLevel',
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['difficultyLevel'], text + '')
              }
            },
            width:110,
            ellipsis: true,
          },
          {
            title:'任务进度',
            align:"center",
            dataIndex: 'progressName',
            width:110,
            ellipsis: true,
          },
          {
            title:'报告编制绩效（元）',
            align:"center",
            dataIndex: 'reportAchievements',
            width:150,
            ellipsis: true,
          },
          {
            title:'绩效提取金额（元）',
            align:"center",
            dataIndex: 'achievementsMoney',
            width:150,
            ellipsis: true,
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:160,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        url: {
          list: "/api/erp/omc/task/achievementsextraction/erpAchievementsExtractionDt/list",
          delete: "/api/erp/omc/task/achievementsextraction/erpAchievementsExtractionDt/delete",
          deleteBatch: "/api/erp/omc/task/achievementsextraction/erpAchievementsExtractionDt/deleteBatch",
          exportXlsUrl: "/api/erp/omc/task/achievementsextraction/erpAchievementsExtractionDt/exportXls",
          importExcelUrl: "/api/erp/omc/task/achievementsextraction/erpAchievementsExtractionDt/importExcel",
          queryProjectById: '/api/erp/project/report/erpProjectReport/queryById'
        },
        dictOptions:{},
        superFieldList:[],
        disableMixinCreated:true,
      }
    },
    created() {
      // 加载数据字典信息
      this.initDictConfig();
      this.columns = this.defColumns
      if (!this.disableMixinCreated) {
        this.initColumns()
      }
      if (this.disabled) {
        this.columns.pop()
      }
      this.columnswidth = this.columns.map(val => {
        return val.width
      })
    },
    computed: {
      // importExcelUrl: function(){
      //   return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      // },
    },
    methods: {
      filterMultiDictText() {
        return filterMultiDictText
      },
      initDictConfig(){
        initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamId', res.result)
          }
        })
        initDictOptions('erp_omc_project,project_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'projectId', res.result)
          }
        })
        initDictOptions('erp_omc_project_task,category_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'taskId', res.result)
          }
        })
        initDictOptions('yjgsnd').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'yjgsYear', res.result)
          }
        })
        initDictOptions('tdnd_type').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'feeYear', res.result)
          }
        })
        initDictOptions('approval_level').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'approvalLevel', res.result)
          }
        })
        initDictOptions('industry_coefficient').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'difficultyLevel', res.result)
          }
        })
        initDictOptions('erp_company_files,file_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'signUnit', res.result)
          }
        })
      },

      getSelectedRowKeys() {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        return ids
      },
      loadData(arg, id) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        this.params = this.getQueryParams() // 查询条件
        this.params.pageNo = 1
        this.params.pageSize = 100
        if(id) {
          this.params.mainId = id
        }
        this.loading = true
        getAction(this.url.list, this.params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((item, index) => {
              item.key = index
            })
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
        this.columns.forEach((val,index) => {
          val.width = this.columnswidth[index]
        })
      },
      getQueryParams() {
        // 获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        // TODO 字段权限控制
        var str = 'id'
        this.columns.forEach(function (value) {
          // 多表头字段
          if (value.dataIndex == null && value.dataIndex === undefined) {
            value.children.forEach(function (item) {
              str += ',' + item.dataIndex.replace('_dictText', '')
            })
          } else {
            str += ',' + value.dataIndex
          }
        })
        return str
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      searchQuery() {
        this.loadData(1)
      },
      superQuery() {
        this.$refs.superQueryModal.show()
      },

      handleDelete: function (key) {
        if (this.dataSource.length == 1) {
          this.dataSource = []
          this.$emit('calculateTotalAmount',this.dataSource)
          return
        }
        this.dataSource.splice(key, 1);
        this.dataSource.forEach((item, index) => {
          item.key = index
        })
        this.$emit('calculateTotalAmount', this.dataSource)

      },
      onDetail(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryProjectById, { id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectModalForm.getDetail(model);
              that.$refs.projectModalForm.title = '项目一览表';
            }
          })
        })
      },
      handleEdit: function (record) {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.disableSubmit = false
      },
      handleAdd: function () {
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.disableSubmit = false
      },

      handleTableChange(pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        // this.loadData()
        // // 清空列表选中
        this.onClearSelected()
      },

      initColumns() {
        // 权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        // this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
        if (this.defColumns) {
          var key = this.$route.name + this.colsettings
          let colSettings = Vue.ls.get(key)
          if (colSettings == null || colSettings == undefined) {
            let allSettingColumns = []
            this.defColumns.forEach(function (item, i, array) {
              allSettingColumns.push(item.dataIndex)
            })
            this.settingColumns = allSettingColumns
            this.columns = this.defColumns
          } else {
            Vue.ls.set(key, colSettings, 7 * 24 * 60 * 60 * 1000)
            this.settingColumns = colSettings
            const cols = this.defColumns.filter(item => {
              if (item.key == 'rowIndex' || item.dataIndex == 'action') {
                return true
              }
              if (colSettings.includes(item.dataIndex)) {
                return true
              }
              return false
            })
            this.columns = cols
          }
        }
      },
      dataOne(data, flag) {
        if(flag) {
          this.dataSource.push(data)
          this.dataSource.forEach((item, index) => {
            item.key = index
          })
        } else {
          this.dataSource.splice(data.key,1,data);
        }
        this.$emit('calculateTotalAmount',this.dataSource)
      },
      submitForm() {
        return this.dataSource
      },

      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'projectId',text:'项目id',dictCode:''})
        fieldList.push({type:'string',value:'projectName',text:'项目名称',dictCode:''})
        fieldList.push({type:'string',value:'year',text:'业绩归属年度',dictCode:''})
        fieldList.push({type:'string',value:'signUnit',text:'签订单位',dictCode:''})
        fieldList.push({type:'string',value:'categoryName',text:'业务名称',dictCode:''})
        fieldList.push({type:'string',value:'taskId',text:'任务id',dictCode:''})
        fieldList.push({type:'string',value:'feeTeamId',text:'费用所属团队',dictCode:''})
        fieldList.push({type:'string',value:'feeTeamName',text:'费用所属团队名称',dictCode:''})
        fieldList.push({type:'string',value:'feeYear',text:'费用所属年度',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'contractAmount',text:'合同额',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'taskContractAmount',text:'分配合同额',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'realCollectionPaymentMoney',text:'回款额',dictCode:''})
        fieldList.push({type:'string',value:'approvalLevel',text:'审批级别',dictCode:''})
        fieldList.push({type:'string',value:'difficultyLevel',text:'难易程度',dictCode:''})
        fieldList.push({type:'string',value:'progressName',text:'任务进度',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'reportAchievements',text:'报告编制绩效',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'achievementsMoney',text:'绩效提取金额',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
